﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.EntityFrameworkCore;
using Rj_GsInsurance.Server.DataBaseContext;
using Rj_GsInsurance.Server.DataBaseContext.Entities;
using Rj_GsInsurance.Server.Extensions;
using Rj_GsInsurance.Server.Models.InsurMsgDataInput;
using Rj_GsInsurance.Server.Models.InsurMsgDataOutput;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using Wpf.Ui;
using Wpf.Ui.Controls;

namespace Rj_GsInsurance.Client.ViewModels
{
    public partial class ReconciliationViewModel : ObservableObject
    {
        [ObservableProperty]
        private DateTime? _beginTime;
        [ObservableProperty]
        private DateTime? _endTime;        
        [ObservableProperty]
        private string _HospNo;
        [ObservableProperty]
        private ObservableCollection<TotalReconciliationResultVeiwModel> _TotalReconciliationResult;
        [ObservableProperty]
        private ObservableCollection<DetaileReconciliationResultViewModel> _DetaileReconciliationResult;

        public HisDbContext HisDbContext { get; private set; }
        public ISnackbarService SnackbarService { get; private set; }

        public ReconciliationViewModel(HisDbContext hisDbContext, ISnackbarService snackbarService)
        {
            HisDbContext = hisDbContext;
            SnackbarService = snackbarService;
        }



        /// <summary>
        /// 总额对账
        /// </summary>
        /// <param name="param"></param>
        [RelayCommand]
        public async void OnTotalReconciliation(object param)
        {
            if (BeginTime == null || EndTime == null)
            {
                SnackbarService.Show(
                        "警告!",
                        $"请选择对账时间段",
                        ControlAppearance.Danger,
                        new SymbolIcon(SymbolRegular.Fluent24),
                        TimeSpan.FromSeconds(30)
                    );
                return;
            }
            var beginTime = BeginTime.Value.ToString("yyyyMMdd000000");
            var endTime = EndTime.Value.ToString("yyyyMMdd235959");

            //var insurWorkInjurySettlements = from patientBill in HisDbContext.Set<IoTbPatientBill>()
            //                                 join insurSettlement in HisDbContext.Set<InsurWorkInjurySettlement>()
            //                                 on patientBill.YbSerialNo equals insurSettlement.SetlId
            //                                 where patientBill.Status == 0 & patientBill.ChareTypeId == 177 & insurSettlement.Status == 1 & long.Parse(insurSettlement.SetlTime) >= long.Parse(beginTime) & long.Parse(insurSettlement.SetlTime) <= long.Parse(endTime)
            //                                 select insurSettlement;

            List<InsurWorkInjurySettlement> injurySettlements = await HisDbContext.InsurWorkInjurySettlements.FromSqlRaw($"select iwis.* from IO_Tb_PatientBill itpb inner join Insur_WorkInjury_Settlement iwis on itpb.YbSerialNo=iwis.bill_id where itpb.ChareTypeId ='177' and iwis.status =1 and itpb.Status =0 and iwis.setl_time between '{beginTime}' and '{endTime}'").ToListAsync();
            //var injurySettlements = await insurWorkInjurySettlements.ToListAsync();
            if (injurySettlements == null || injurySettlements.Count() == 0)
            {
                SnackbarService.Show(
                        "警告!",
                        $"未查询到需要对账的数据",
                        ControlAppearance.Danger,
                        new SymbolIcon(SymbolRegular.Fluent24),
                        TimeSpan.FromSeconds(30)
                    );
                return;
            }

            TotalReconciliationInput input = new TotalReconciliationInput()
            {
                Ylfze = injurySettlements.Sum(s => decimal.Parse(s.MedfeeSumamt ?? "0")).ToString(),
                Xjzf = injurySettlements.Sum(s => decimal.Parse(s.PsnCashPay ?? "0")).ToString(),
                Gsjjzf = injurySettlements.Sum(s => decimal.Parse(s.InjuryPay ?? "0")).ToString(),
                Kssj = beginTime,
                Zzsj = endTime,
            };

            try
            {
                var insurMsgOut = input.Excute<TotalReconciliationInput, TotalReconciliationOutput>("1120");
                TotalReconciliationResult = new ObservableCollection<TotalReconciliationResultVeiwModel>()
                {
                    new TotalReconciliationResultVeiwModel()
                    {
                        Ylfze=input.Ylfze,
                        Xjzf=input.Xjzf,
                        Gsjjzf=input.Gsjjzf,
                        Kssj=input.Kssj,
                        Zzsj=input.Zzsj,
                        Dzjg=insurMsgOut.output.Dzjg=="1"?"平":"不平",
                        Zxylfze=insurMsgOut.output.Zxjjzfhj,
                        Zxxjzfze=insurMsgOut.output.Zxxjzfhj,
                        Zzjjzfhj=insurMsgOut.output.Zxjjzfhj,
                    }
                };
                if (TotalReconciliationResult.Any(a => a.Dzjg == "不平"))
                {
                    SnackbarService.Show(
                        "警告!",
                        $"对账不平",
                        ControlAppearance.Danger,
                        new SymbolIcon(SymbolRegular.Fluent24),
                        TimeSpan.FromSeconds(30)
                    );
                    return;
                }
                else
                {
                    SnackbarService.Show(
                        "提示!",
                        $"成功",
                        ControlAppearance.Success,
                        new SymbolIcon(SymbolRegular.Fluent24),
                        TimeSpan.FromSeconds(30)
                    );
                    return;
                }
            }
            catch (Exception ex)
            {
                SnackbarService.Show(
                        "警告!",
                        $"对账失败!{ex.Message}",
                        ControlAppearance.Danger,
                        new SymbolIcon(SymbolRegular.Fluent24),
                        TimeSpan.FromSeconds(30)
                    );
                return;
            }

        }
        /// <summary>
        /// 明细对账
        /// </summary>
        /// <param name="param"></param>
        [RelayCommand]
        public async void OnDetaileReconciliation(object param)
        {
            if (string.IsNullOrWhiteSpace(HospNo))
            {
                SnackbarService.Show(
                        "警告!",
                        $"请输入住院号!",
                        ControlAppearance.Danger,
                        new SymbolIcon(SymbolRegular.Fluent24),
                        TimeSpan.FromSeconds(30)
                    );
                return;
            }
            var patient = await HisDbContext.IoTbInPatients.Where(w => w.HospNo == HospNo.Trim()).FirstOrDefaultAsync();
            if (patient == null)
            {
                SnackbarService.Show(
                        "警告!",
                        $"未查询到住院就诊数据!",
                        ControlAppearance.Danger,
                        new SymbolIcon(SymbolRegular.Fluent24),
                        TimeSpan.FromSeconds(30)
                    );
                return;
            }
            var patientBills = await HisDbContext.IoTbPatientBills.Where(w=>w.RegNo== patient.RegNo && w.ChareTypeId== 177&&w.Status==0).ToListAsync();
            var patientBill=patientBills?.FirstOrDefault();
            var setlId= patientBill?.YbSerialNo;
            var regNo= patientBill?.RegNo;
            if (string.IsNullOrWhiteSpace(setlId))
            {
                SnackbarService.Show(
                        "警告!",
                        $"未查询到住院结算数据!",
                        ControlAppearance.Danger,
                        new SymbolIcon(SymbolRegular.Fluent24),
                        TimeSpan.FromSeconds(30)
                    );
                return;
            }
            var regedition=await HisDbContext.IoTbCenterRegisterStatuses.Where(w=>w.RegNo==regNo).FirstOrDefaultAsync();
            var jzlsh = regedition?.Jzdyh;
            if (string.IsNullOrWhiteSpace(jzlsh))
            {
                SnackbarService.Show(
                        "警告!",
                        $"未查询到医保就诊流水号!",
                        ControlAppearance.Danger,
                        new SymbolIcon(SymbolRegular.Fluent24),
                        TimeSpan.FromSeconds(30)
                    );
                return;
            }
            var injurySettlement=await HisDbContext.InsurWorkInjurySettlements.Where(w => w.SetlId == setlId&&w.Status==1).FirstOrDefaultAsync();

            DetaileReconciliationInput input = new DetaileReconciliationInput()
            {
                Jzlsh = jzlsh,
            };
            try
            {
                var insurMsgOut = input.Excute<DetaileReconciliationInput, DetaileReconciliationOutput>("1130");
                DetaileReconciliationResult = new ObservableCollection<DetaileReconciliationResultViewModel>()
                {
                    new DetaileReconciliationResultViewModel()
                    {
                        BillId=patientBill?.BillId.ToString(),
                        HisYlfze=(patientBill?.UnReimburseAmount+patientBill?.ReimburseAmount)?.ToString(),
                        Received_amount=patientBill?.ReceivedAmount?.ToString(),
                        Change_amount=patientBill?.ChangeAmount?.ToString(),
                        Diff_amount=patientBill?.DiffAmount?.ToString(),
                        Return_amount=patientBill?.ReturnAmount?.ToString(),
                        Deduction_amt=patientBill?.DeductionAmt?.ToString(),
                        Ylfze=insurMsgOut.output.Fyze,
                        Cxjze=insurMsgOut.output.Cxjze,
                        Zlfyze=insurMsgOut.output.Zlfyze,
                        Zffyze=insurMsgOut.output.Zffyze,
                        Sjts=insurMsgOut.output.Sjts,
                    }
                };
            }
            catch (Exception ex)
            {
                SnackbarService.Show(
                        "警告!",
                        $"对账失败!{ex.Message}",
                        ControlAppearance.Danger,
                        new SymbolIcon(SymbolRegular.Fluent24),
                        TimeSpan.FromSeconds(30)
                    );
                return;
            }
        }
    }

    public partial class TotalReconciliationResultVeiwModel : ObservableObject
    {
        [ObservableProperty]
        private string _ylfze;
        [ObservableProperty]
        private string _xjzf;
        [ObservableProperty]
        private string _gsjjzf;
        [ObservableProperty]
        private string _kssj;
        [ObservableProperty]
        private string _zzsj;
        [ObservableProperty]
        private string _dzjg;
        [ObservableProperty]
        private string _zxylfze;
        [ObservableProperty]
        private string _zxxjzfze;
        [ObservableProperty]
        private string _zzjjzfhj;
    }

    public partial class DetaileReconciliationResultViewModel:ObservableObject
    {
        [ObservableProperty]
        private string _BillId;
        [ObservableProperty]
        private string _hisYlfze;
        [ObservableProperty]
        private string _received_amount;
        [ObservableProperty]
        private string _change_amount;
        [ObservableProperty]
        private string _diff_amount;
        [ObservableProperty]
        private string _return_amount;
        [ObservableProperty]
        private string _deduction_amt;
        [ObservableProperty]
        private string _ylfze;
        [ObservableProperty]
        private string _cxjze;
        [ObservableProperty]
        private string _zlfyze;
        [ObservableProperty]
        private string _zffyze;
        [ObservableProperty]
        private string _sjts;
    }
}
